package com.plat.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.plat.security.entity.DictionaryType;
import com.plat.security.entity.DictionaryTypeGroup;
import com.plat.service.IBaseService;
import com.plat.service.IDictionaryGroupService;
import com.plat.service.IDictionaryService;
import com.plat.tag.core.json.AjaxJson;
import com.plat.tag.core.json.AjaxUtils;
import com.plat.tag.core.json.TreeGrid;
import com.plat.tag.core.json.ValidForm;
import com.plat.util.StringUtil;

@Controller
@RequestMapping("/dictionaryController.do")
public class DictionaryController extends BaseController<DictionaryType> {

    @Autowired
    private IDictionaryService service;

    @Autowired
    private IDictionaryGroupService serviceGroup;

    @Override
    public IBaseService<DictionaryType> getService() {
        return service;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(params = "typeGridTree")
    @ResponseBody
    public List<TreeGrid> typeGridTree(HttpServletRequest request, TreeGrid treegrid) {
        List<TreeGrid> treeGrids = new ArrayList<TreeGrid>();
        if (treegrid.getId() != null) {
            Long id = Long.valueOf(treegrid.getId().substring(1));
            DictionaryTypeGroup typeGroup = serviceGroup.get(id);
            Criteria cri = getService().createCriteria();
            cri.add(Restrictions.eq("TSTypegroup.typegroupid", typeGroup.getTypegroupid()));
            List<DictionaryType> typeList = cri.list();
            for (DictionaryType obj : typeList) {
                TreeGrid treeNode = new TreeGrid();
                treeNode.setId("T" + obj.getId());
                treeNode.setText(obj.getTypename());
                treeNode.setCode(obj.getTypecode());
                treeGrids.add(treeNode);
            }
        } else {
            Criteria cri = serviceGroup.createCriteria();
            List<DictionaryTypeGroup> typeGroupList = cri.list();
            for (DictionaryTypeGroup obj : typeGroupList) {
                TreeGrid treeNode = new TreeGrid();
                treeNode.setId("G" + obj.getId());
                treeNode.setText(obj.getTypegroupname());
                treeNode.setCode(obj.getTypegroupcode());
                treeNode.setState("closed");
                treeGrids.add(treeNode);
            }
        }

        return treeGrids;
    }

    @RequestMapping(params = "toTypeEdit")
    protected ModelAndView toTypeEdit(DictionaryType type, String typegroupid) {
        ModelAndView mv = new ModelAndView("dictionary/addgroup");
        if (type.getId() != null) {
            mv.addObject("entity", getService().get(type.getId()));
        }
        mv.addObject("typegroupid", typegroupid);
        return mv;
    }

    @RequestMapping(params = "doSaveTypeGroup")
    @ResponseBody
    protected AjaxJson doSaveTypeGroup(final DictionaryTypeGroup typeGroup) {

        return new AjaxUtils() {

            @Override
            protected Object busCall() throws Exception {
                if (typeGroup.getId() == null) {
                    Criteria cri = serviceGroup.createCriteria();
                    Long max = (Long) cri.setProjection(Projections.max("typegroupid")).uniqueResult();
                    if (max == null) {
                        max = 0L;
                    }
                    typeGroup.setTypegroupid(max + 1);
                }
                serviceGroup.save(typeGroup);
                serviceGroup.refleshTypeGroupCach();
                return null;
            }
        }.excuteJson("字典项添加成功", "字典项添加失败");
    }

    @RequestMapping(params = "doSaveType")
    @ResponseBody
    protected AjaxJson doSaveType(final DictionaryType type) {

        return new AjaxUtils() {

            @Override
            protected Object busCall() throws Exception {
                if (type.getId() == null) {
                    Criteria cri = getService().createCriteria();
                    Long max = (Long) cri.setProjection(Projections.max("typeid")).uniqueResult();
                    if (max == null) {
                        max = 0L;
                    }
                    type.setTypeid(max + 1);
                }
                type.setTSTypegroup(serviceGroup.get(type.getTSTypegroup().getId()));
                getService().save(type);
                serviceGroup.refleshTypesCach(type);
                return null;
            }
        }.excuteJson("参数项添加成功", "参数项添加失败");
    }

    @RequestMapping(params = "checkTypeGroup")
    @ResponseBody
    public ValidForm checkTypeGroup(HttpServletRequest request, String param, String code) {
        ValidForm v = new ValidForm();

        List<DictionaryTypeGroup> typegroups = serviceGroup.findBy("typegroupcode", param);
        if (typegroups.size() > 0 && !code.equals(param)) {
            v.setInfo("字典项已经存在");
            v.setStatus("n");
        }
        return v;
    }

    @RequestMapping(params = "toEditGroup")
    public ModelAndView toEditGroup(String id, String root) {
        ModelAndView mv = new ModelAndView(root + "/add");
        try {
            if (StringUtil.isNotEmpty(id)) {
                DictionaryTypeGroup t = serviceGroup.get(getEntityId(id));
                mv.addObject("entity", t);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mv;
    }

    @RequestMapping(params = "doDeleteGroup")
    @ResponseBody
    public AjaxJson doDeleteGroup(final String id) throws Exception {

        return new AjaxUtils() {
            @Override
            protected Object busCall() {
                if (id.startsWith("G")) {//删除组
                    DictionaryTypeGroup group = serviceGroup.get(getEntityId(id.substring(1)));
                    serviceGroup.remove(group);
                    serviceGroup.refleshTypeGroupCach();
                    serviceGroup.clearTypes(group.getTypegroupcode());
                } else {//删除单个类型
                    DictionaryType type = getService().get(Long.valueOf(id.substring(1)));
                    getService().remove(type);
                    serviceGroup.refleshTypesCach(type);
                }
                return null;
            }
        }.excuteJson("数据删除成功!", "数据删除失败");
    }

}
